import React, { useState, useEffect } from "react";
import { Modal, Steps, Button, Alert, Typography } from "antd";
import { getAvailableAccount } from "../../services/mainApp";
import { AccountInfo } from "../../types/account";
import { AxiosError } from "axios";

const { Step } = Steps;

interface PostAvailableAccountModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

// Define more specific types for error responses
interface ConfirmationErrorData {
  message: string;
  confirmation_required: true;
  data: {
    current_account_details: {
      requestUsage?: number;
      maxRequestUsage?: number;
    };
  };
}

interface GeneralErrorData {
  message: string;
  code?: number;
}

type ErrorResponse = ConfirmationErrorData | GeneralErrorData;

const initialSteps = [
  {
    key: "fetch",
    title: "获取账号",
    description: "从服务器获取一个可用的账号...",
  },
  {
    key: "swap",
    title: "配置环境",
    description: "关闭进程、重置ID并注入新账号...",
  },
  {
    key: "finish",
    title: "完成",
    description: "所有操作已成功执行。",
  },
];

export const PostAvailableAccountModal: React.FC<
  PostAvailableAccountModalProps
> = ({ open, onClose, onSuccess }) => {
  const [steps, setSteps] = useState(initialSteps);
  const [currentStep, setCurrentStep] = useState(0);
  const [stepStatus, setStepStatus] = useState<"process" | "finish" | "error">(
    "process"
  );
  const [isLoading, setIsLoading] = useState(false);
  const [errorInfo, setErrorInfo] = useState<{
    title: string;
    subTitle: string;
  } | null>(null);
  const [needsConfirmation, setNeedsConfirmation] = useState(false);

  const resetState = () => {
    setSteps(initialSteps);
    setCurrentStep(0);
    setStepStatus("process");
    setIsLoading(false);
    setErrorInfo(null);
    setNeedsConfirmation(false);
  };

  const handleClose = () => {
    resetState();
    onClose();
  };

  const startProcess = async (maliceSwitch = false) => {
    setIsLoading(true);
    setStepStatus("process");
    setErrorInfo(null);
    setNeedsConfirmation(false);

    try {
      // Step 1: Get Account
      setCurrentStep(0);
      setSteps((prev) =>
        prev.map((s) =>
          s.key === "fetch"
            ? { ...s, status: "process", description: "正在从云端获取账号..." }
            : s
        )
      );
      const response = await getAvailableAccount(maliceSwitch);
      const apiResponse = response.data;

      // Case 1: Handle Confirmation Request (data is an object with confirmation_required)
      if (
        apiResponse.data &&
        typeof apiResponse.data === "object" &&
        "confirmation_required" in apiResponse.data &&
        apiResponse.data.confirmation_required
      ) {
        const confirmationData = apiResponse.data;
        const details = confirmationData.current_account_details;
        const subTitle = `${apiResponse.message} (当前用量: ${details.requestUsage}/${details.maxRequestUsage})`;
        setErrorInfo({ title: "需要您确认", subTitle });
        setNeedsConfirmation(true);
        setStepStatus("error");
        setIsLoading(false);
        return;
      }

      // Case 2: Handle Successful Account Fetch (message is an object with account details)
      if (
        apiResponse.message &&
        typeof apiResponse.message === "object" &&
        "token" in apiResponse.message &&
        "email" in apiResponse.message
      ) {
        const newAccountInfo = apiResponse.message as Partial<AccountInfo> & {
          email: string;
          token: string;
        };

        setSteps((prev) =>
          prev.map((s) => (s.key === "fetch" ? { ...s, status: "finish" } : s))
        );

        // Step 2: Full local swap (Close, Reset, Inject)
        setCurrentStep(1);
        setSteps((prev) =>
          prev.map((s) =>
            s.key === "swap"
              ? { ...s, status: "process", description: "正在替换账号..." }
              : s
          )
        );

        const swapResult = await window.electronAPI.runTask<{
          success: boolean;
          message: string;
        }>("switch-available-account", {
          email: newAccountInfo.email,
          token: newAccountInfo.token,
        });

        if (!swapResult.success) {
          throw new Error(swapResult.message);
        }

        setSteps((prev) =>
          prev.map((s) => (s.key === "swap" ? { ...s, status: "finish" } : s))
        );

        // Step 3: Finish
        setCurrentStep(2);
        setStepStatus("finish");

        // Notify the parent component about the success
        if (onSuccess) {
          onSuccess();
        }
      } else {
        // Case 3: Handle unexpected response structure
        throw new Error("从服务器返回的响应格式不正确或无效。");
      }
    } catch (error) {
      setStepStatus("error");
      const axiosError = error as AxiosError<ErrorResponse>;

      if (axiosError.response?.data?.message) {
        const errorData = axiosError.response.data;
        if (
          "confirmation_required" in errorData &&
          errorData.confirmation_required
        ) {
          const details = errorData.data.current_account_details;
          const subTitle = `${errorData.message} (当前用量: ${details.requestUsage}/${details.maxRequestUsage})`;
          setErrorInfo({ title: "需要您确认", subTitle });
          setNeedsConfirmation(true);
        } else {
          setErrorInfo({ title: "操作失败", subTitle: errorData.message });
        }
      } else {
        setErrorInfo({
          title: "操作失败",
          subTitle: (error as Error).message || "发生未知错误",
        });
      }
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (open) {
      // Reset state every time the modal opens
      resetState();
      startProcess();
    }
  }, [open]);

  const renderFooter = () => {
    if (
      stepStatus === "finish" ||
      (stepStatus === "error" && !needsConfirmation)
    ) {
      return [
        <Button key="close" type="primary" onClick={handleClose}>
          完成
        </Button>,
      ];
    }
    if (needsConfirmation) {
      return [
        <Button key="cancel" onClick={handleClose}>
          取消
        </Button>,
        <Button
          key="confirm"
          type="primary"
          danger
          onClick={() => startProcess(true)}
          loading={isLoading}
        >
          强制切换
        </Button>,
      ];
    }
    return [
      <Button key="close" onClick={handleClose} disabled={isLoading}>
        关闭
      </Button>,
    ];
  };

  return (
    <Modal
      title={<Typography.Title level={4}>获取并注入可用账号</Typography.Title>}
      open={open}
      onCancel={handleClose}
      width={600}
      footer={renderFooter()}
      closable={!isLoading}
      maskClosable={!isLoading}
    >
      <Typography.Paragraph type="secondary" style={{ marginBottom: 24 }}>
        此操作将从云端获取一个可用的Cursor账号，并自动为您完成替换。流程开始后请勿关闭应用。
      </Typography.Paragraph>
      <Steps
        current={currentStep}
        status={stepStatus}
        size="small"
        style={{ marginBottom: 24 }}
      >
        {steps.map((step) => (
          <Step
            key={step.key}
            title={step.title}
            description={step.description}
          />
        ))}
      </Steps>

      {errorInfo && (
        <Alert
          // message={errorInfo.title}
          description={errorInfo.subTitle}
          type={needsConfirmation ? "warning" : "error"}
        />
      )}
    </Modal>
  );
};
